package com.example.yilanchatserver.business.freechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yilanchatserver.application.controller.vo.UtopiaKnowledgeContentListVO;
import com.example.yilanchatserver.application.controller.vo.UtopiaSpaceListVO;
import com.example.yilanchatserver.business.freechat.*;
import com.example.yilanchatserver.business.freechat.service.RedisService;
import com.example.yilanchatserver.business.freechat.service.UtopiaService;
import com.example.yilanchatserver.business.freechat.service.dto.*;
import com.example.yilanchatserver.common.ConvertUtils;
import com.example.yilanchatserver.dal.knowledge.batchmapper.KnowledgeBatchMapper;
import com.example.yilanchatserver.dal.knowledge.entity.ContentlistEntity;
import com.example.yilanchatserver.dal.knowledge.entity.KnowledgeEntity;
import com.example.yilanchatserver.dal.knowledge.mapper.KnowledgeMapper;
import com.example.yilanchatserver.dal.knowledge.mapper.ContentlistMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.reflections.Reflections.log;


@Component
public class UtopiaServiceImpl implements UtopiaService {



    @Value("${utopia.appId}")
    private String appId;

    @Value("${utopia.appSecret}")
    private String appSecret;

    @Value("${utopia.tokenURL}")
    private String tokenURL;

    @Value("${utopia.chatURL}")
    private String chatURL;

    @Value("${utopia.chatStreaming}")
    private String chatStreaming;

    @Value("${utopia.resetURL}")
    private String resetURL;

    @Value("${utopia.knowledge.knowledgeListURL}")
    private String knowledgeListURL;

    @Value("${utopia.knowledge.createKnowledgeURL}")
    private String createKnowledgeURL;

    @Value("${utopia.knowledge.updateKnowledgeURL}")
    private String updateKnowledgeURL;

    @Value("${utopia.knowledge.deleteKnowledgeURL}")
    private String deleteKnowledgeURL;

    @Value("${utopia.text.textContentURL}")
    private String textContentURL;

    @Value("${utopia.text.createTextContentURL}")
    private String createTextContentURL;

    @Value("${utopia.text.getTextContentURL}")
    private String getTextContentURL;

    @Value("${utopia.text.deleteTextContentURL}")
    private String deleteTextContentURL;

    @Value("${utopia.doc.docContentURL}")
    private String docContentURL;

    @Value("${utopia.doc.createDocContentURL}")
    private String createDocContentURL;

    @Value("${utopia.doc.getDocContentURL}")
    private String getDocContentURL;

    @Value("${utopia.doc.deleteDocContentURL}")
    private String deleteDocContentURL;

    @Value("${utopia.web.webContentURL}")
    private String webContentURL;

    @Value("${utopia.web.createWebContentURL}")
    private String createWebContentURL;

    @Value("${utopia.web.getWebContentURL}")
    private String getWebContentURL;

    @Value("${utopia.web.deleteWebContentURL}")
    private String deleteWebContentURL;

    @Value("${utopia.qa.qaContentURL}")
    private String qaContentURL;

    @Value("${utopia.qa.createQaContentURL}")
    private String createQaContentURL;

    @Value("${utopia.qa.getQaContentURL}")
    private String getQaContentURL;

    @Value("${utopia.qa.deleteQaContentURL}")
    private String deleteQaContentURL;

    @Value("${utopia.space.createSpace}")
    private String createSpaceURL;

    @Value("${utopia.space.spaceList}")
    private String spaceListURL;

    @Value("${utopia.role.createRole}")
    private String createRoleURL;

    @Value("${utopia.role.publishRole}")
    private String publishRoleURL;

    @Value("${utopia.role.updateRole}")
    private String updateRoleURL;

    @Value("${utopia.role.getRoleId}")
    private String getRoleIdURL;

    @Value("${utopia.role.getRoleInfo}")
    private String getRoleInfoURL;


    private String tokenKey = "utopia:token:";

    @Resource
    private RedisService redisService;

    @Resource
    private UtopiaWebClient utopiaWebClient;

    @Resource
    private KnowledgeBatchMapper knowledgeBatchMapper;

    @Resource
    private KnowledgeMapper knowledgeMapper;

    @Resource
    private ContentlistMapper contentlistMapper;

    public String getToken() throws Exception {
        String token = redisService.get(tokenKey);
        if(StringUtils.isEmpty(token)){
            Map paramsMap = new HashMap();
            paramsMap.put("appId", appId);
            paramsMap.put("appSecret", appSecret);
            Map header = new HashMap<>();
            header.put("Content-type", "application/json; charset=utf-8");
            String response = HttpUtilClient.sendPostJson(tokenURL, JSON.toJSONString(paramsMap), header);
            Map resultMap = JSON.parseObject(response, Map.class);
            Boolean isSuccess = (Boolean) resultMap.get("success");
            if(!isSuccess){
                throw new Exception("获取token失败：" + (String)resultMap.get("message"));
            }
            else{
                Map data = (Map) resultMap.get("data");
                token = (String) data.get("access_token");
                Integer time = (Integer) data.get("expires_in");
                redisService.set(tokenKey, token, time, TimeUnit.SECONDS);
            }
        }
        return token;
    }

    public String connectHTTP(String URL, String params) throws Exception {
        String token = getToken();
        Map header = new HashMap<>();
        header.put("Content-type", "application/json; charset=utf-8");
        header.put("Authorization", "Bearer "+token);
        return HttpUtilClient.sendPostJson(URL, params, header);
    }

    public String connectHTTP(String URL, Map<String, String> params) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("Content-type", "application/json; charset=utf-8");
        header.put("Authorization", "Bearer "+token);
        return HttpUtilClient.sendGet(URL, params, header);
    }

    public <T> Map commonConnection(String URL, T inputDTO) throws Exception {

        Map paramsMap = JSON.parseObject(JSON.toJSONString(inputDTO), Map.class);
        String response = connectHTTP(URL, JSON.toJSONString(paramsMap));
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        else{
            Map data = (Map) resultMap.get("data");
            return data;
        }
    }

    public Map commonConnection(String URL, Map inputDTO) throws Exception {

        String response = connectHTTP(URL, JSON.toJSONString(inputDTO));
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        else{
            Map data = (Map) resultMap.get("data");
            return data;
        }
    }

    public UtopiaSpaceListVO getSpaceList(UtopiaSpaceListDTO utopiaSpaceListDTO) throws Exception {
        Map paramsMap = JSON.parseObject(JSON.toJSONString(utopiaSpaceListDTO), Map.class);
        paramsMap.put("name", utopiaSpaceListDTO.getProduct());
        paramsMap.remove("userId");
        paramsMap.remove("branch");
        Map data = commonConnection(spaceListURL, paramsMap);
        return JSON.parseObject(JSON.toJSONString(data), UtopiaSpaceListVO.class);
    }


    @Override
    public String getChat(UtopiaChatDTO utopiaChatDTO) throws Exception {
        Map paramsMap = JSON.parseObject(JSON.toJSONString(utopiaChatDTO), Map.class);
        String response = connectHTTP(chatURL, JSON.toJSONString(paramsMap));
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        String answer = null;
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        else{
            Map data = (Map) resultMap.get("data");
            String responseSource = (String) data.get("responseSource");
            if(Objects.equals(responseSource, "bot_response_censor") || Objects.equals(responseSource, "user_response_censor")){
                throw new Exception("回答或返回包含敏感信息：" + (String) data.get("message"));
            } else if (Objects.equals(responseSource, "chara_faq")) {
                answer = (String) data.get("qas");
            } else {
                answer = (String) data.get("content");
            }
        }
        return answer;
    }
    @Override
    public ResponseEntity<StreamingResponseBody> chatStreaming(UtopiaChatDTO utopiaChatDTO)  throws Exception  {
        String token = getToken();
        System.out.println("token data: " + token); // 添加日志
        String url = chatStreaming + "/" + token;
        Map paramsMap = JSON.parseObject(JSON.toJSONString(utopiaChatDTO), Map.class);

        StreamingResponseBody streamingResponseBody = outputStream -> {
            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/x-www-form-urlencoded");
            HttpUtilClient.sendGetWithStream(url, paramsMap, header, inputStream -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                    String line;
                    String history = "";
                    while ((line = reader.readLine()) != null) {
                        if (line.isEmpty()) {
                            continue;
                        }
                        log.info("Received line: {}", line);
                        // 从SSE数据中提取JSON字符串
                        String jsonData = line.substring(line.indexOf("{"));
                        Map<String, Object> dataMap = new HashMap<>();
                        Map<String, Object> resultMap = JSON.parseObject(jsonData, Map.class);
                        String content = (String) resultMap.get("content");
                        content = content == null ? "" : content.substring(history.length());
                        history = (String) resultMap.get("content") == null ? "" : (String) resultMap.get("content");
                        dataMap.put("roleId", resultMap.get("roleId"));
                        dataMap.put("content", content);
                        if (line.contains("未找到知识")) {
                            log.info("Received 未找到知识: {}");
                            // TODO: 处理特定逻辑
                            // 向Map中添加新字段
                            dataMap.put("invalid", false);
                            // 将修改后的Map转换回JSON字符串
                            String modifiedJson = JSON.toJSONString(dataMap);
                            String dataToSend = "data: " + modifiedJson + "\n\n";  // 将接收到的数据写入响应流
                            outputStream.write(dataToSend.getBytes());
                            outputStream.flush();  // 确保数据被发送
                            break;
                        } else {
                            log.info("正常转发请求");
                            // 向Map中添加新字段
                            dataMap.put("invalid", true);
                            // 将修改后的Map转换回JSON字符串
                            String modifiedJson = JSON.toJSONString(dataMap);
                            String dataToSend = "data: " + modifiedJson + "\n\n";  // 将接收到的数据写入响应流
                            outputStream.write(dataToSend.getBytes());
                            outputStream.flush();  // 确保数据被发送
                        }
                    }
                } catch (Exception e) {
                    log.error("Error reading SSE: {}", e.getMessage());
                    // 向客户端发送错误信息（如果需要）
                    String errorData = "data: Error occurred\n\n";
                    try {
                        outputStream.write(errorData.getBytes());
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                    try {
                        outputStream.flush();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            });
        };

        return ResponseEntity.ok().contentType(MediaType.valueOf("text/event-stream")).body(streamingResponseBody);
    }

    @Override
    public void resetChat(UtopiaResetDTO utopiaResetDTO) throws Exception {
        Map data = commonConnection(resetURL, utopiaResetDTO);
    }

    @Override
    public List<YiLanKnowledgeData> getKnowledgeList(YiLanGetKnowledgeBaseListDTO yiLanGetKnowledgeBaseListDTO) throws Exception {
        QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", yiLanGetKnowledgeBaseListDTO.getUserId());
        queryWrapper.eq("product", yiLanGetKnowledgeBaseListDTO.getProduct());
        queryWrapper.eq("virtual_role_uk", yiLanGetKnowledgeBaseListDTO.getVirtualRoleUk());
        queryWrapper.eq("service", "lingxin");
        List<KnowledgeEntity> knowledgeEntities = knowledgeMapper.selectList(queryWrapper);
        List<YiLanKnowledgeData> utopiaKnowledgeListVOS = new ArrayList<>();
        for(KnowledgeEntity k: knowledgeEntities){
            Map m = JSON.parseObject(JSON.toJSONString(k), Map.class);
            m.put("id", m.remove("knowledgeId"));
            YiLanKnowledgeData u = JSON.parseObject(JSON.toJSONString(m), YiLanKnowledgeData.class);
            utopiaKnowledgeListVOS.add(u);
        }

        return utopiaKnowledgeListVOS;

    }


    @Override
    public Long createKnowledge(YiLanCreateKnowledgeBaseDTO utopiaCreateKnowledgeDTO) throws Exception {
        Map paramsMap = new HashMap<>();
        paramsMap.put("name", utopiaCreateKnowledgeDTO.getUserId());
        String response = connectHTTP(createKnowledgeURL, JSON.toJSONString(paramsMap));
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        } else {
            Map data = (Map) resultMap.get("data");
            KnowledgeEntity knowledgeEntity = ConvertUtils.convert(utopiaCreateKnowledgeDTO, KnowledgeEntity.class);
            knowledgeEntity.setService("lingxin");
            knowledgeEntity.setKnowledgeId(Long.valueOf(data.get("id").toString()));
            knowledgeEntity.setDeleteFlag(0);
            knowledgeMapper.insert(knowledgeEntity);
            return knowledgeEntity.getKnowledgeId();
        }
    }


    @Override
    public void updateKnowledge(YiLanCreateKnowledgeBaseDTO utopiaUpdateKnowledgeDTO) throws Exception {
//        Map data = commonConnection(updateKnowledgeURL, utopiaUpdateKnowledgeDTO);
        QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("knowledge_id", utopiaUpdateKnowledgeDTO.getId());
        queryWrapper.eq("service", "lingxin");
        KnowledgeEntity knowledgeEntity = knowledgeMapper.selectOne(queryWrapper);
        knowledgeEntity.setName(utopiaUpdateKnowledgeDTO.getName());

        knowledgeMapper.updateById(knowledgeEntity);
    }


    @Override
    public void deleteKnowledge(YiLanDeleteKnowledgeDTO yiLanDeleteKnowledgeDTO) throws Exception {
        Map data = commonConnection(deleteKnowledgeURL, yiLanDeleteKnowledgeDTO);
        QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("knowledge_id", yiLanDeleteKnowledgeDTO.getId());
        queryWrapper.eq("service", "lingxin");
        KnowledgeEntity knowledgeEntity = knowledgeMapper.selectOne(queryWrapper);
        knowledgeMapper.deleteById(knowledgeEntity);

    }


    @Override
    public UtopiaKnowledgeContentListVO getKnowledgeContentList(YiLanKnowledgeContentListDTO yiLanKnowledgeContentListDTO) throws Exception {
        Map paramsMap = JSON.parseObject(JSON.toJSONString(yiLanKnowledgeContentListDTO), Map.class);
        String branch = (String) paramsMap.get("branch");
        String response = null;
        switch (branch){
            case "text":
                paramsMap.put("content", paramsMap.remove("searchName"));
                response = connectHTTP(textContentURL, JSON.toJSONString(paramsMap));
                break;
            case "doc":
                paramsMap.put("name", paramsMap.remove("searchName"));
                response = connectHTTP(docContentURL, JSON.toJSONString(paramsMap));
                break;
            case "web":
                response = connectHTTP(webContentURL, JSON.toJSONString(paramsMap));
                break;
            case "qa":
                paramsMap.put("data", paramsMap.remove("searchName"));
                response = connectHTTP(qaContentURL, JSON.toJSONString(paramsMap));
                break;
            default:
                throw new Exception();
        }
        Map resultMap = JSON.parseObject(response, Map.class);
//        已经有一次faqid的隔离了
//        // 清洗数据 resultMap 只有在表 contentlistEntity 中存在id的数据才返回。
//        List<ContentlistEntity> contentlistEntities = contentlistMapper.selectList(null);
//        List<Map> contentlistMap = (List<Map>) resultMap.get("data");
//        List<Map> returnMap = new ArrayList<>();
//        for(Map m: contentlistMap){
//            for(ContentlistEntity c: contentlistEntities){
//                if(Objects.equals(m.get("id"), c.getId())){
//                    returnMap.add(m);
//                }
//            }
//        }
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        Map data = (Map) resultMap.get("data");

        return JSON.parseObject(JSON.toJSONString(data), UtopiaKnowledgeContentListVO.class);
    }

    @Override
    public Map createKnowledgeContent(YiLanCreateKnowledgeContentDTO yiLanCreateKnowledgeContentDTO) throws Exception {
        Map paramsMap = JSON.parseObject(JSON.toJSONString(yiLanCreateKnowledgeContentDTO), Map.class);
        String branch = (String) paramsMap.get("branch");
        String response = null;
        // 查找数据库， 找出对应 userId 和 product 和 branch的数据size 如果大于100 则返回错误
        QueryWrapper<ContentlistEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", yiLanCreateKnowledgeContentDTO.getUserId());
        queryWrapper.eq("product", yiLanCreateKnowledgeContentDTO.getProduct());
        queryWrapper.eq("branch", yiLanCreateKnowledgeContentDTO.getBranch());
        queryWrapper.eq("service", "lingxin");
        List<ContentlistEntity> contentlistEntities = contentlistMapper.selectList(queryWrapper);
        if(contentlistEntities.size() >= 100){
            String errorType = "最多支持导入100篇文章";
            if (branch == "text") {
                errorType = "最多支持100条文本知识";
            } else if (branch == "doc") {
                errorType = "最多支持导入100篇文章";
            } else if (branch == "web") {
                errorType = "最多支持100个网址内容";
            }
            throw new Exception(errorType);
        }
        switch (branch){
            case "text":
                response = connectHTTP(createTextContentURL, JSON.toJSONString(paramsMap));
                break;
            case "doc":
                paramsMap.put("name", paramsMap.remove("content"));
                response = connectHTTP(createDocContentURL, JSON.toJSONString(paramsMap));
                break;
            case "web":
                response = connectHTTP(createWebContentURL, JSON.toJSONString(paramsMap));
                break;
            case "qa":
                response = connectHTTP(createQaContentURL, JSON.toJSONString(paramsMap));
                break;
            default:
                throw new Exception();
        }
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        Map data = (Map) resultMap.get("data");
        if(yiLanCreateKnowledgeContentDTO.getId() == null){
            ContentlistEntity contentlistEntity = ConvertUtils.convert(yiLanCreateKnowledgeContentDTO, ContentlistEntity.class);
            contentlistEntity.setId((String) data.get("id"));
            contentlistEntity.setDeleteFlag(0);
            contentlistEntity.setProduct(yiLanCreateKnowledgeContentDTO.getProduct());
            contentlistEntity.setUserId(yiLanCreateKnowledgeContentDTO.getUserId());
            contentlistEntity.setBranch(branch);
            contentlistEntity.setService("lingxin");
            contentlistMapper.insert(contentlistEntity);
        }
        return data;
    }

    @Override
    public Map getKnowledgeContent(YiLanGetKnowledgeContentDTO yiLanGetKnowledgeContentDTO) throws Exception {
        Map paramsMap = JSON.parseObject(JSON.toJSONString(yiLanGetKnowledgeContentDTO), Map.class);
        String branch = (String) paramsMap.get("branch");
        String response = null;
        Map<String, String> getParams = new HashMap<>();
        getParams.put("id", (String) paramsMap.get("id"));
        switch (branch){
            case "text":
                response = connectHTTP(getTextContentURL, getParams);
                break;
            case "doc":
                paramsMap.put("name", paramsMap.remove("content"));
                response = connectHTTP(getDocContentURL, getParams);
                break;
            case "web":
                response = connectHTTP(getWebContentURL, getParams);
                break;
            case "qa":
                response = connectHTTP(getQaContentURL, getParams);
                break;
            default:
                throw new Exception();
        }
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        Map data = (Map) resultMap.get("data");
        return data;
    }


    @Override
    public void deleteKnowledgeContent(YiLanDeleteKnowledgeContentDTO yiLanDeleteKnowledgeContentDTO) throws Exception {
        Map paramsMap = JSON.parseObject(JSON.toJSONString(yiLanDeleteKnowledgeContentDTO), Map.class);
        String branch = (String) paramsMap.get("branch");
        String response = null;
        //  只有在表 contentlistEntity 中存在id的数据才能清除
        QueryWrapper<ContentlistEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", yiLanDeleteKnowledgeContentDTO.getId());
        queryWrapper.eq("service", "lingxin");
        ContentlistEntity contentlistEntity = contentlistMapper.selectOne(queryWrapper);
        if (contentlistEntity == null) {
            throw new Exception("操作失败：用户对改知识库数据无权限");
        }
        switch (branch){
            case "text":
                response = connectHTTP(deleteTextContentURL + "?id=" + paramsMap.get("id"), JSON.toJSONString(paramsMap));
                break;
            case "doc":
                paramsMap.put("name", paramsMap.remove("content"));
                response = connectHTTP(deleteDocContentURL + "?id=" + paramsMap.get("id"), JSON.toJSONString(paramsMap));
                break;
            case "web":
                response = connectHTTP(deleteWebContentURL + "?id=" + paramsMap.get("id"), JSON.toJSONString(paramsMap));
                break;
            case "qa":
                response = connectHTTP(deleteQaContentURL + "?id=" + paramsMap.get("id"), JSON.toJSONString(paramsMap));
                break;
            default:
                throw new Exception();
        }
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        } else {
            contentlistMapper.deleteById(contentlistEntity);
        }
    }

    @Override
    public Map createSpace(YiLanCreateSpaceDTO yiLanCreateSpaceDTO) throws Exception {
        // 查询空间，没有再创建
        UtopiaSpaceListVO utopiaSpaceListVO = getSpaceList(JSON.parseObject(JSON.toJSONString(yiLanCreateSpaceDTO), UtopiaSpaceListDTO.class));
        if(utopiaSpaceListVO.getItemCount() > 0){
            for (Map returnMap : utopiaSpaceListVO.getContent()){
                if(Objects.equals((String) returnMap.get("roleNames"), yiLanCreateSpaceDTO.getUserId())){
                    // 判断数据库中userId对应数据的virtualRoleUk是否和传入的virtualRoleUk相同，如果相同则返回 returnMap 否则不进行任何操作
                    QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("user_id", yiLanCreateSpaceDTO.getUserId());
                    queryWrapper.eq("product", yiLanCreateSpaceDTO.getProduct());
                    queryWrapper.eq("service", "lingxin");
                    List<KnowledgeEntity> knowledgeEntity = knowledgeMapper.selectList(queryWrapper);
                    // 打印日志 knowledgeEntity数据
                    System.out.println(knowledgeEntity);

                    if(knowledgeEntity.size() > 0){
                        // 循环 knowledgeEntity 判断是否有相同的 virtualRoleUk
                        for(KnowledgeEntity k: knowledgeEntity){
                            if(Objects.equals(k.getVirtualRoleUk(), yiLanCreateSpaceDTO.getVirtualRoleUk())){
                                return returnMap;
                            }
                        }
                    }
                }
            }


        }
        // 创建空间
        String name = yiLanCreateSpaceDTO.getProduct();
        Map paramsMap = new HashMap<>();
        paramsMap.put("name", name);
        String response = connectHTTP(createSpaceURL, JSON.toJSONString(paramsMap));
        Map resultMap = JSON.parseObject(response, Map.class);
        Boolean isSuccess = (Boolean) resultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        Map data = (Map) resultMap.get("data");
        data.remove("updateTime");
        data.remove("companyId");
        data.remove("pageSize");
        data.remove("pageNum");
        data.remove("delFlag");
        UtopiaCreateRoleDTO utopiaCreateRoleDTO = new UtopiaCreateRoleDTO();
        utopiaCreateRoleDTO.setSpaceId(Long.valueOf(data.get("id").toString()));
        utopiaCreateRoleDTO.setName(yiLanCreateSpaceDTO.getUserId());
        List<String> greetingList = new ArrayList<>();
        greetingList.add("你好");
        utopiaCreateRoleDTO.setGreeting(greetingList);
        List<Map<String, String>> replyList = new ArrayList<>();
        Map<String, String> tmp = new HashMap<>();
        tmp.put("content", "未找到知识");
        replyList.add(tmp);
        utopiaCreateRoleDTO.setReplyChats(replyList);
        // 创建角色
        String roleResponse = connectHTTP(createRoleURL, JSON.toJSONString(utopiaCreateRoleDTO));
        Map roleResultMap = JSON.parseObject(roleResponse, Map.class);
        isSuccess = (Boolean) roleResultMap.get("success");
        Map roleData = (Map) roleResultMap.get("data");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)roleResultMap.get("message"));
        }
//        发布角色
        Map publishParamsMap = new HashMap<>();
        // 打印 roleResultMap
        System.out.println(((Map<?, ?>) roleResultMap.get("data")).get("id"));
        publishParamsMap.put("id", ((Map<?, ?>) roleResultMap.get("data")).get("id"));
        String publishRoleResponse = connectHTTP(publishRoleURL, JSON.toJSONString(publishParamsMap));
        Map publishRoleResultMap = JSON.parseObject(publishRoleResponse, Map.class);
        isSuccess = (Boolean) publishRoleResultMap.get("success");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)roleResultMap.get("message"));
        }
        // 创建知识库
//        Map knowledgeListData = createKnowledge(utopiaCreateSpaceDTO.getUserId());
//        // 将知识库链接到角色
//        UtopiaUpdateRoleDTO utopiaUpdateRoleDTO = JSON.parseObject(JSON.toJSONString(utopiaCreateRoleDTO), UtopiaUpdateRoleDTO.class);
//        List<Long> faqsList = new ArrayList<>();
//        faqsList.add(Long.valueOf(knowledgeListData.get("id").toString()));
//        utopiaUpdateRoleDTO.setFaqs(faqsList);
//        utopiaUpdateRoleDTO.setId(Long.valueOf(roleData.get("id").toString()));
//        String updateRoleResponse = connectHTTP(updateRoleURL, JSON.toJSONString(utopiaUpdateRoleDTO));
//        Map updateRoleResultMap = JSON.parseObject(updateRoleResponse, Map.class);
//        isSuccess = (Boolean) updateRoleResultMap.get("success");
//        if(!isSuccess){
//            throw new Exception("发送失败：" + (String)updateRoleResultMap.get("message"));
//        }

//        UtopiaPublishRoleDTO utopiaPublishRoleDTO = new UtopiaPublishRoleDTO();
//        utopiaPublishRoleDTO.setId(Long.valueOf(roleData.get("id").toString()));
//
//        String publishResponse = connectHTTP(publishRoleURL, JSON.toJSONString(utopiaPublishRoleDTO));
//        Map rolePublishMap = JSON.parseObject(publishResponse, Map.class);
//        isSuccess = (Boolean) rolePublishMap.get("success");
//        if(!isSuccess){
//            throw new Exception("发送失败：" + (String)rolePublishMap.get("message"));
//        }

        data.put("roleSize", 1);
        data.put("roleNames", roleData.get("name"));
        return data;
    }

    @Override
    public List updateRole(YiLanUpdateRoleDTO yiLanUpdateRoleDTO) throws Exception {
        List<String> greetingList = new ArrayList<>();
        greetingList.add("你好");
        yiLanUpdateRoleDTO.setGreeting(greetingList);
        List<Map<String, String>> replyList = new ArrayList<>();
        Map<String, String> tmp = new HashMap<>();
        tmp.put("content", "未找到知识");
        replyList.add(tmp);
        yiLanUpdateRoleDTO.setReplyChats(replyList);
        Map tmpMap = JSON.parseObject(JSON.toJSONString(yiLanUpdateRoleDTO), Map.class);
        tmpMap.put("name", tmpMap.remove("userId"));
        // 创建角色
        String roleResponse = connectHTTP(updateRoleURL, JSON.toJSONString(tmpMap));
        Map roleResultMap = JSON.parseObject(roleResponse, Map.class);
        Boolean isSuccess = (Boolean) roleResultMap.get("success");
        Map roleData = (Map) roleResultMap.get("data");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)roleResultMap.get("message"));
        }
        return (List) roleData.get("faqs");
    }

    @Override
    public Map getRoleId(Long spaceId) throws Exception {
        Map tmpMap = new HashMap<>();
        tmpMap.put("spaceId", spaceId);
        String roleResponse = connectHTTP(getRoleIdURL, JSON.toJSONString(tmpMap));
        Map roleResultMap = JSON.parseObject(roleResponse, Map.class);
        Map roleData = (Map) roleResultMap.get("data");
        Boolean isSuccess = (Boolean) roleResultMap.get("success");
        List roleList = (List) roleData.get("content");
        if(!isSuccess){
            throw new Exception("发送失败：" + (String)roleResultMap.get("message"));
        }
        Map data = (Map) roleList.get(0);
        String roleId = data.get("id").toString();
        // 下面为 get请求
        // String roleInfoResponse = connectHTTP(getRoleInfoURL + roleId, JSON.toJSONString(tmpMap));
        // 替换为
        Map<String, String> getParams = new HashMap<>();
        getParams.put("id", roleId);
        String roleInfoResponse = connectHTTP(getRoleInfoURL + roleId, getParams);
        Map roleInfoResultMap = JSON.parseObject(roleInfoResponse, Map.class);
        Boolean isInfoSuccess = (Boolean) roleInfoResultMap.get("success");
        Map roleInfoData = (Map) roleInfoResultMap.get("data");
        if(!isInfoSuccess){
            throw new Exception("发送失败：" + (String)roleInfoResultMap.get("message"));
        }
        List faqs = (List) roleInfoData.get("faqs");
        // 返回faqs 和 roleI
        Map returnMap = new HashMap();
        returnMap.put("faqs", faqs);
        returnMap.put("roleId", roleId);
        return returnMap;
    }

    @Override
    public Flux<String> send(UtopiaStreamDTO utopiaStreamDTO) throws Exception {
        String authToken = getToken();
        return Flux.create(emitter -> {
            UtopiaSubscriber subscriber = new UtopiaSubscriber(emitter);
            Flux<String> zhiPuResponse =
                    utopiaWebClient.getChatResponse(utopiaStreamDTO, authToken);
            zhiPuResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }
}
